import 'dart:io';

import 'package:core_package/core_package.dart';
import 'package:core_package/share/my_font_weight.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_unionad/main/protocol_page.dart';
import 'package:flutter_app_unionad/request/login_request.dart';
import 'package:flutter_app_unionad/ui/login/binding_mobile_page.dart';
import 'package:flutter_app_unionad/ui/login/register_page.dart';
import 'package:flutter_app_unionad/ui/login/widget/login_input_widget.dart';
import 'package:flutter_app_unionad/view_model/page_manager_view_model.dart';

class LoginForPasswordPage extends StatefulWidget {
  static const String routeName = "/loginForPasswordPage";

  final bool isLaunch;

  const LoginForPasswordPage({Key? key, this.isLaunch = false}) : super(key: key);

  @override
  _LoginForPasswordPageState createState() => _LoginForPasswordPageState();
}

class _LoginForPasswordPageState extends State<LoginForPasswordPage> {
  bool isOpen = true;
  bool selectProtocol = false;
  String? mobile;
  String? password;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        child: buildContent(context),
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
        },
      ),
    );
  }

  Widget buildContent(BuildContext context) {
    return Container(
      height: SizeFill.screenHeight,
      width: SizeFill.screenWidth,
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage(
            MyAssetsImages.setAssetsImagesPath("icon_login_bg"),
          ),
          fit: BoxFit.fill,
        ),
      ),
      child: SingleChildScrollView(
        child: Container(
          child: Column(
            children: [
              SizedBox(height: SizeFill.statusHeight! + SizeFill.setRx(20)),
              Row(
                children: [
                  Expanded(child: MySizeBox()),
                  InkWell(
                    onTap: () {
                      NavigatorUtil.pop(context);
                    },
                    child: Text(
                      "验证码登录",
                      style: TextStyle(
                        color: MyColors.formHex("#272727FF"),
                        fontSize: MyFont.font14,
                      ),
                    ),
                  ),
                  SizedBox(width: 20),
                ],
              ),
              SizedBox(height: SizeFill.setRx(40)),
              Image.asset(
                MyAssetsImages.setAssetsImagesPath("icon_logo_1"),
                width: SizeFill.setRx(131.67),
                height: SizeFill.setRx(124.33),
              ),
              SizedBox(height: SizeFill.setRx(48)),
              Text(
                "让 生 活 更 美 好",
                style: TextStyle(
                  fontFamily: "assets/fonts/ZhanKuWenYiTi_2.ttf",
                  fontWeight: MyFontWeight.regular,
                  color: MyColors.formHex("#272727FF"),
                  fontSize: SizeFill.setRx(16),
                ),
              ),
              MySizeBox(height: 30),
              buildInputContent(),
              MySizeBox(height: 20),
            ],
          ),
        ),
      ),
    );
  }

  Widget buildInputContent() {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(SizeFill.setRx(7)),
      ),
      margin: EdgeInsets.symmetric(horizontal: SizeFill.setRx(17)),
      child: Padding(
        padding: EdgeInsets.only(
          left: SizeFill.setRx(37),
          right: SizeFill.setRx(37),
          top: SizeFill.setRx(30),
          bottom: SizeFill.setRx(30),
        ),
        child: buildInputList(),
      ),
    );
  }

  Widget buildInputList() {
    return Column(
      children: [
        Text(
          "用户名密码登录",
          style: TextStyle(
            fontSize: MyFont.font14,
            color: MyColors.formHex("#272727FF"),
            fontWeight: MyFontWeight.bold,
          ),
        ),
        MySizeBox(height: 30),
        LoginInputWidget(
          maxLength: 11,
          placeholder: "请输入手机号",
          leftIcon: "icon_account",
          keyboardType: TextInputType.number,
          inputTextTapChange: (value) {
            mobile = value;
          },
        ),
        MySizeBox(height: 13),
        LoginInputWidget(
          maxLength: 20,
          placeholder: "请输入密码",
          leftIcon: "icon_password",
          keyboardType: TextInputType.visiblePassword,
          inputTextTapChange: (value) {
            password = value;
          },
          obscureText: isOpen,
          rightIcon: InkWell(
            onTap: () {
              setState(() {
                isOpen = !isOpen;
              });
            },
            child: Container(
              alignment: Alignment.center,
              padding: EdgeInsets.only(
                right: SizeFill.setRx(10),
              ),
              child: Image.asset(
                MyAssetsImages.setAssetsImagesPath(!isOpen ? "icon_open_eye" : "icon_close_eye"),
                width: SizeFill.setRx(16),
                height: SizeFill.setRx(10),
              ),
            ),
          ),
        ),

        MySizeBox(height: 30),
        buildButton("登录", () {
          loginOnTap();
        }),
        MySizeBox(height: 30),
        // buildThirdLogin(),
        // MySizeBox(height: 13),
        // buildButton("注册", () {
        //   registerOnTap();
        // }),
        MySizeBox(height: 12),
        buildProtocolWidget(),
      ],
    );
  }

  Widget buildThirdLogin() {
    List icons;
    if (Platform.isIOS) {
      icons = ["icon_we_chat", /*"icon_alipay", "icon_apple",*/ "icon_iphone"];
    } else {
      icons = ["icon_we_chat", /*"icon_alipay",*/ "icon_iphone"];
    }
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: List.generate(icons.length, (index) {
        return Padding(
          padding: EdgeInsets.only(right: index == (icons.length - 1) ? 0 : SizeFill.setRx(38)),
          child: GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              thirdLoginOnTap(icons[index]);
            },
            child: Image.asset(
              MyAssetsImages.setAssetsImagesPath(
                icons[index],
              ),
              width: SizeFill.setRx(15),
              height: SizeFill.setRx(15),
            ),
          ),
        );
      }),
    );
  }

  Widget buildButton(String title, Function() onTap) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        onTap();
      },
      child: Container(
        width: SizeFill.setRx(267),
        height: SizeFill.setRx(40),
        decoration: BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              MyAssetsImages.setAssetsImagesPath("icon_button_bg_1"),
            ),
          ),
        ),
        alignment: Alignment.center,
        child: Text(
          title,
          style: TextStyle(
            color: MyColors.formHex("#FFFFFFFF"),
            fontSize: MyFont.font14,
            fontWeight: MyFontWeight.bold,
          ),
        ),
      ),
    );
  }

  Widget buildProtocolWidget() {
    TextStyle blackTS = TextStyle(
      color: MyColors.color_43_44_48,
      fontSize: 11.px,
      fontWeight: MyFontWeight.regular,
    );
    TextStyle blueTS = TextStyle(
      color: Color.fromARGB(255, 15, 187, 222),
      fontSize: 11.px,
      fontWeight: MyFontWeight.regular,
    );
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () {
            setState(() {
              selectProtocol = !selectProtocol;
            });
          },
          child: Container(
            padding: EdgeInsets.all(SizeFill.setRx(5)),
            child: Image.asset(
              MyAssetsImages.setAssetsImagesPath(selectProtocol ? "icon_select" : "icon_unselect"),
              width: SizeFill.setRx(14),
              height: SizeFill.setRx(14),
            ),
          ),
        ),
        SizedBox(width: 3),
        Expanded(
          child: Text.rich(
            TextSpan(
              children: [
                TextSpan(
                  text: '我已阅读，且完全通用并接受',
                  style: blackTS,
                ),
                // TextSpan(
                //   text: '《中国移动认证服务条款》',
                //   style: blueTS,
                // ),
                // TextSpan(
                //   text: '和',
                //   style: blackTS,
                // ),
                TextSpan(
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      //
                      NavigatorUtil.push(context, ProtocolPage.routeName, arguments: 1);
                    },
                  text: '《注册协议》',
                  style: blueTS,
                ),
                TextSpan(
                  text: '和',
                  style: blackTS,
                ),
                TextSpan(
                  text: '《服务隐私协议》',
                  style: blueTS,
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      NavigatorUtil.push(context, ProtocolPage.routeName, arguments: 0);
                    },
                ),
              ],
            ),
            // strutStyle: StrutStyle(forceStrutHeight: true, height: 0.58, leading: 1),
          ),
        )
      ],
    );
  }

  void loginOnTap() {
    if(!selectProtocol){
      ShowToastWidget.showToast(msg: "请同意相关协议");
      return;
    }
    if (!isPhoneString(mobile)) {
      ShowToastWidget.showToast(msg: "手机号格式不对");
      return;
    }
    if (password == null || !isPassword(password!)) {
      ShowToastWidget.showToast(msg: "密码长度为6-16位");
      return;
    }
    ProgressDialog.showProgress(context);

    LoginRequest.login(password: password, phone: mobile, type: 1).then((value) {
      ProgressDialog.dismiss(context);

      if (value) {
        Navigator.pop(context);
        PagesManagerViewModel.updateType(context, PagesManagerType.app);
      }
    });
  }

  void registerOnTap() {
    NavigatorUtil.push(context, RegisterPage.routeName);
  }

  void thirdLoginOnTap(String type) {
    if (type == "icon_we_chat") {
      // 微信登录
    } else if (type == "icon_alipay") {
      //支付宝登录
    } else if (type == "icon_apple") {
      //苹果登录

    } else if (type == "icon_iphone") {
      //手机验证码登录
      NavigatorUtil.push(context, BindingMobilePage.routeName);
    }
  }
}
